package com.tien.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.tien.dao.MenuDao;
import com.tien.model.Group;
import com.tien.model.Menu;
import com.tien.utils.ConstantsTool;

/**
 * @author tienxin
 * @E-mail g.tianxin@gmail.com
 * @version 2012-2-19 上午01:45:54
 */
@SuppressWarnings("rawtypes")
@Component
public class MenuDaoImpl extends BaseDaoImpl implements MenuDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<Menu> findAllMenus(Long menuGroupId) {
		/*
		String hql = "from Menu order by SORT_ID";
		return this.getEntitiesByHQL(hql);
		*/
		String hql = "";
		// group is admin default get all menus
		if(Long.parseLong(ConstantsTool.ADMIN_MENU_GROUP_ID) == menuGroupId){
			hql = "from Menu order by SORT_ID";
			return this.getEntitiesByHQL(hql);
		}
		else
			hql = "from Group where id = ? and GROUP_TYPE = 'MENU'";
		Group group = (Group) this.getEntitiesByHQL(hql, menuGroupId).get(0);
		List<Menu> menus = new ArrayList<Menu>();
		for (Menu m : group.getMenus()) {
			menus.add(m);
		}
		return menus;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Long saveMenu(Menu menu) {
		Menu menuLoad = (Menu) this.findById(Menu.class, menu.getId());
		menuLoad.setName(menu.getName());
		menuLoad.setUrl(menu.getUrl());
		this.updateEntity(menuLoad);
		return menu.getId();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Menu findMenuById(Long id) {
		// TODO Auto-generated method stub
		return (Menu) this.findById(Menu.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Long addMenu(Menu menu) {
		// TODO Auto-generated method stub
		this.saveEntity(menu);
		return menu.getId();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void deleteMenuById(Long id) {
		this.deleteEntityById(Menu.class, id);
	}

}
